package com.ews.onlineexchange.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.model.User;

/**
 * 中介机构查询本用户已经中标后被取消的交易
 * 
 * @author admin
 *
 */
@Model
@RolesAllowed( value = "supplier" )
public class SupplierCancelledTradeList extends EntityQuery<Trade> {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;

	@Inject
	UserService					userService;

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Trade> entity ) {
		User loginedUser = userService.getLoginedUser();
		List<Predicate> restrictions = new ArrayList<Predicate>();
		restrictions.add( cb.isTrue( entity.<Boolean>get( "apply" ) ) );

		Join<Trade, ServiceSupplier> supplier = entity.join( "supplier" );
		restrictions.add( cb.equal( supplier.get( "username" ), loginedUser.getUsername() ) );

		Join<Trade, Bulletin> bulletin = entity.join( "bulletin" );
		// 11-09 针对直接选取 只有当公告审核成功后 才能查到数据
		restrictions.add( cb.isTrue( bulletin.<Boolean>get( "auditResult" ) ) );
		restrictions.add( cb.isTrue( bulletin.<Boolean>get( "over" ) ) );
		restrictions.add( cb.equal( bulletin.get( "tradeStatus" ), TradeStatus.Agreed ) );
		restrictions.add( cb.equal( bulletin.get( "successTrade" ), entity ) );
		restrictions.add( cb.isTrue( bulletin.<Boolean>get( "cancelled" ) ) );

		String projectName = (String) getParameterValues().get( "projectName" );
		if ( !StringUtils.isBlank( projectName ) )
			restrictions.add( cb.like( bulletin.get( "projectName" ), getStringRestriction( projectName ) ) );

		String serialNumber = (String) getParameterValues().get( "serialNumber" );
		if ( !StringUtils.isBlank( serialNumber ) )
			restrictions.add( cb.like( bulletin.get( "serialNumber" ), getStringRestriction( serialNumber ) ) );
		return restrictions;
	}

	public SupplierCancelledTradeList() {
		super();
		setOrder( "createDate desc" );
	}

}
